package com.sh.sales.happysales.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sh.polymedicine.happysale.result.SimpleResult;
import com.sh.polymedicine.happysale.service.envelop.HappySaleManager;
import com.sh.sales.happysales.R;
import com.sh.sales.happysales.app.AppData;
import com.sh.sales.happysales.app.utils.LoginOutUtil;
import com.sh.sales.happysales.base.BaseActivity;
import com.sh.sales.happysales.imgutil.LoadImageManager;
import com.sh.sales.happysales.service.LoginObsever;
import com.sh.sales.happysales.view.NewToast;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Subscriber;

/**
 * Created by zhouyucheng on 2017/9/15.
 */

public class CashToWechatActivity extends BaseActivity implements LoginObsever {
    @BindView(R.id.set_back)
    ImageView setBack;
    @BindView(R.id.profect_next)
    TextView profectNext;
    @BindView(R.id.cash_notice)
    TextView cashNotice;
    @BindView(R.id.cash_value)
    TextView cashValue;
    @BindView(R.id.cash_entervalue)
    EditText cashEntervalue;
    @BindView(R.id.cash_all)
    TextView cashAll;
    @BindView(R.id.cash_getbtn)
    Button cashGetbtn;
    @BindView(R.id.m_view)
    LinearLayout mView;


    private PopupWindow popupWindow;
    private DisplayImageOptions options;
    private String cashNoticetext;
    private double valueCash;
    private String userSign;
    private double enterCash;
    private int refreshSignTag = -1;

    private Subscriber<SimpleResult> decripSubscriber;
    private Subscriber<SimpleResult> cashToChartSubscriber;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cashtowe);
        ButterKnife.bind(this);
        mAppManager.addActivity(this);
        mLoginObserable.registerObserver(this);
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.bg_start_page)
                .showImageForEmptyUri(R.drawable.bg_start_page)
                .displayer(new RoundedBitmapDisplayer(4))
                .showImageOnFail(R.drawable.bg_start_page)
                .imageScaleType(ImageScaleType.EXACTLY)
                .considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        Intent m = getIntent();
        valueCash = m.getDoubleExtra("cashValue", 0.0);
        cashValue.setText(valueCash + "");
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        cashcontent();
    }

    private void cashcontent() {
        refreshSignTag = 1;
        if (decripSubscriber != null) {
            if (decripSubscriber.isUnsubscribed()) {
                decripSubscriber.unsubscribe();
            }
        }
        decripSubscriber = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                Log.i("CaptureActivity", "onError: " + e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())){
                    String message =e.getCause().getCause().getMessage();
                    NewToast.makeText(CashToWechatActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(CashToWechatActivity.this);
                    }
                }else if (HappySaleManager.DATA_NULL.equals(e.getMessage())){
                    NewToast.makeText(CashToWechatActivity.this, e.getCause().getMessage());
                }else{
                    NewToast.makeText(CashToWechatActivity.this, "获取提现说明失败");
                }
            }

            @Override
            public void onNext(SimpleResult result) {
                cashNoticetext = result.getImage();
            }

        };
        mHappySaleManager.withdrawDescription(userSign, decripSubscriber).subscribe(decripSubscriber);
    }

    @OnClick({R.id.set_back, R.id.cash_notice, R.id.cash_all, R.id.cash_getbtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.set_back:
                mAppManager.finishActivity(this);
                break;
            case R.id.cash_notice:
                showCashNotice();
                break;
            case R.id.cash_all:
                cashEntervalue.setText(valueCash + "");
                break;
            case R.id.cash_getbtn:
                connectCashto();
                break;
        }
    }

    private void connectCashto() {
        enterCash = Double.parseDouble(cashEntervalue.getText().toString());
        if (enterCash < 0 && enterCash > valueCash) {
            NewToast.makeText(CashToWechatActivity.this, "输入金额不在可提取范围之内");
            return;
        }
        refreshSignTag = 2;
        if (cashToChartSubscriber != null) {
            if (cashToChartSubscriber.isUnsubscribed()) {
                cashToChartSubscriber.unsubscribe();
            }
        }
        cashToChartSubscriber = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i("CaptureActivity", "onError: " + e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())){
                    String message =e.getCause().getCause().getMessage();
                    NewToast.makeText(CashToWechatActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(CashToWechatActivity.this);
                    }
                }else if (HappySaleManager.DATA_NULL.equals(e.getMessage())){
                    NewToast.makeText(CashToWechatActivity.this, e.getCause().getMessage());
                }else{
                    NewToast.makeText(CashToWechatActivity.this, "提现失败,请检查网络");
                }
            }

            @Override
            public void onNext(SimpleResult result) {
                showCashend();
            }
        };
        mHappySaleManager.cash(enterCash + "", userSign, cashToChartSubscriber).subscribe(cashToChartSubscriber);
    }

    private void showCashend() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.pop_cashend, null);
        contentview.setFocusable(true); // 这个很重要
        contentview.setFocusableInTouchMode(true);
        popupWindow = new PopupWindow(contentview, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        ImageView img = (ImageView) contentview.findViewById(R.id.set_back);
        Button btnEnd = (Button) contentview.findViewById(R.id.cash_getclose);
        TextView cashgetvalue = (TextView) contentview.findViewById(R.id.cash_getvalue);
        cashgetvalue.setText(enterCash + "");
        btnEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                finish();
            }
        });
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                finish();
            }

        });
        contentview.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popupWindow.dismiss();
                    finish();
                    return true;
                }
                return false;
            }
        });
        popupWindow.showAtLocation(mView, Gravity.CENTER, 0, 0);
    }

    private void showCashNotice() {

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.pop_cash_notice, null);
        contentview.setFocusable(true); // 这个很重要
        contentview.setFocusableInTouchMode(true);
        popupWindow = new PopupWindow(contentview, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        ImageView img = (ImageView) contentview.findViewById(R.id.set_back);
        ImageView imgnotice = (ImageView) contentview.findViewById(R.id.img_notice);
        mLoadImageManager.displayImage(cashNoticetext, imgnotice, LoadImageManager.IMG, options);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        contentview.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    popupWindow.dismiss();
                    return true;
                }
                return false;
            }
        });
        popupWindow.showAtLocation(mView, Gravity.CENTER, 0, 0);

    }

    @Override
    public void refreshUserSign(int Position) {
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        switch (refreshSignTag) {
            case 1:
                cashcontent();
                break;
            case 2:
                connectCashto();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        mLoginObserable.unregisterObserver(this);
        super.onDestroy();
    }
}
